/**
 * Created by lee_mxue on 17/5/8.
 */
import React from "react"
import ReactDOM from "react-dom"
import tools from "../../lib/tools"
import classNames from "classnames"
import { addErrorListener } from "../../lib/handleError"
import weixinShare from "../../lib/weixinShare"
import AJAX from "../../lib/ajax"
import Toast from "../MyPackage/components/Toast"
import Loading from "../../components/Loading"
import ExpressCard from "../../components/ExpressCard/ExpressCard"

require('../../lib/resetFont')
require('./ChooseExpressCompany.less')

class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            current_label: "PRICE",
            card_list: [],
            selected_list: [],
        }
        this.switchLabel = this.switchLabel.bind(this)
    }

    //验证
    verify() {
        //    获取已有信息
        //获取已选柜体信息
        const CabinetSendingInfo_x = JSON.parse(window.localStorage.getItem('CabinetSendingInfo_x'))
        // 收件人信息
        const receiverData = JSON.parse(localStorage.getItem('cabinet_receiverData_x'))
        // 已选快递信息
        const selected_express_company = JSON.parse(localStorage.getItem('selected_express_company'))

        if (!CabinetSendingInfo_x || !receiverData) {
            Toast.error({
                type: "new",
                content: "信息有误"
            })
            setTimeout(this.goBack, 1000)
            return 
        }

        this.setState({
            selectedCabinet: CabinetSendingInfo_x,
            selectReceiverInfo: receiverData,
            selected_express_company
        },()=>{
            this.fetch(2)()
        })
    }
    componentWillMount() {
        addErrorListener()()
        //隐藏分享功能
        weixinShare.hideAll()
        //验证已选柜体和收件人
        this.verify()
    }

    componentDidMount() {
        AJAX.appendBaiduAnalysis()
    }
    openLoading() {
        this.setState({
            loading: true,
            loading_text: "加载中..."
        })
    }
    closeLoading() {
        this.setState({
            loading: false
        })
    }
    fetch(sortby_id) {
        let {selectedCabinet, selectReceiverInfo} = this.state
        return ()=>{
            this.openLoading()
            //获取快递公司列表（ 快递公司id, 保价估值, 排序方式－－－2.价格3.速度(时效)，默认2
            AJAX.request("sending_cab_order_fee_list", {
                sortby: sortby_id,         //排序方式
                cabinet_id: selectedCabinet.id,   //物流中心id
                province_code: selectReceiverInfo.province_code,   //目的省份编码
                city_code: selectReceiverInfo.city_code,   //目的城市编码
                county_code: selectReceiverInfo.county_code,   //目的区县编码
            }, (data) => {
                this.closeLoading()
                if (data.code == 0) {
                    this.setState({
                        card_list: this.filterCardlist(data.body.list),
                        current_label: sortby_id === 2 ? "PRICE" : "TIME" 
                    })
                }else {
                    Toast.error({
                        type: "new",
                        content: "列表获取失败"
                    })
                }
            })
        }
    }

    filterCardlist(list=[]) {
        return list.map(item=>({
            id: item.id,
            tariff_id: item.tariff_id,
            name: item.name,
            is_valid: item.is_valid,
            price: item.price / 100,
            time: item.arrive_time,
            img: item.img
            })
        )
    }

    switchLabel(key) {
        return ()=>{
            if(key === this.state.current_label){
                return 
            }else {
                if(key === "PRICE") {
                    this.fetch(2)()
                }else if(key === "TIME") {
                    this.fetch(3)()
                }
            }
        }
    }

    expressChange(selected_list = []) {
        this.setState({
            selected_list
        })
    }

    goBack() {
        window.location.href = "./CabinetSendingHeader"
    }

    submit() {
        const {selected_list} = this.state
        if(selected_list.length > 0) {
            localStorage.setItem("selected_express_company", JSON.stringify(selected_list))
        }else {
            localStorage.removeItem("selected_express_company")
        }
        this.goBack()
    }

    render() {
        const {current_label, card_list, selected_express_company} = this.state
        const price_cls = current_label === "PRICE" ? "current-cell" : ""
        const time_cls = current_label === "TIME" ? "current-cell" : ""
        return (
            <div className="ChooseExpressCompany lux-pb80">
                <div className="header lux-h90">
                    <div className={classNames("cell lux-w100", price_cls)}
                        onClick={this.switchLabel("PRICE")}>
                        价格
                    </div>
                    <div className={classNames("cell lux-w100", time_cls)}
                         onClick={this.switchLabel("TIME")}>
                        时效
                    </div>
                </div>
                <div className="banner lux-h46">
                    多选几家快递公司可以防止订单因无人响应而取消哦！
                </div>
                {card_list.length > 0 
                ? <ExpressCard 
                  cardList={card_list}
                  selectedList={selected_express_company} 
                  className=""
                  onChange={this.expressChange.bind(this)} />
                : null
                }
                <div className="button lux-h80" onClick={this.submit.bind(this)}>
                    确定
                </div>
                <Loading show={this.state.loading}/>
            </div>
        )
    }
}
ReactDOM.render(<App />, document.getElementById('app'))
if (module.hot) {
    module.hot.accept()
}